package com.jilian.mydemo.modul.user.activity;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.jaeger.library.StatusBarUtil;
import com.jilian.mydemo.Constant;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.base.CommonActivity;
import com.jilian.mydemo.common.dto.LoginDto;
import com.jilian.mydemo.factory.Factoty;
import com.jilian.mydemo.modul.exam.ui.StartExamActivity;
import com.jilian.mydemo.modul.main.ui.MainActivity;
import com.jilian.mydemo.modul.main.ui.WelcomeActivity;
import com.jilian.mydemo.modul.user.viewmodel.UserViewModel;
import com.jilian.mydemo.utils.NumberUtils;
import com.jilian.mydemo.utils.SPUtil;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.utils.Utils;
import com.jilian.mydemo.views.ClearEditText;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

/**
 * 登录fff
 * weishixiong
 * 2019-03-17
 */
public class LoginActivity extends CommonActivity implements BDLocationListener {
    private RelativeLayout rlCancel;
    private ClearEditText etPhone;
    private ClearEditText etPwd;
    private RelativeLayout rlEye;
    private ImageView ivEye;
    private TextView tvLoginRegister;
    private TextView tvLoginForgetPwd;
    private TextView tvLogin;
    private boolean mbDisplayFlg;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        rlCancel = (RelativeLayout) findViewById(R.id.rl_cancel);
        etPhone = (ClearEditText) findViewById(R.id.et_phone);
        etPwd = (ClearEditText) findViewById(R.id.et_pwd);
        rlEye = (RelativeLayout) findViewById(R.id.rl_eye);
        ivEye = (ImageView) findViewById(R.id.iv_eye);
        tvLoginRegister = (TextView) findViewById(R.id.tv_login_register);
        tvLoginForgetPwd = (TextView) findViewById(R.id.tv_login_forget_pwd);
        tvLogin = (TextView) findViewById(R.id.tv_login);
        etPhone.setText(SPUtil.getData("login_sp","phone",String.class,null));
    }

    @Override
    public void initData() {
        SPUtil.clearData(Constant.SP_VALUE.SP);
        MyApplication.clearSpecifyActivities(new Class[]{WelcomeActivity.class});
        startLocationCilent();
    }
    /**
     * 开启定位
     */
    private void startLocationCilent() {
        // 申请权限
        MyApplication.getInstance().mLocationClient.start();
        MyApplication.getInstance().mLocationClient.registerLocationListener(this);
    }
    @Override
    public void initListener() {
        rlCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });
        tvLoginRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
            }
        });
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(etPhone.getText().toString()) && !TextUtils.isEmpty(etPwd.getText().toString())) {
                    tvLogin.setBackgroundResource(R.drawable.shape_btn_login_normal);
                    tvLogin.setEnabled(true);
                } else {
                    tvLogin.setBackgroundResource(R.drawable.shape_btn_login_dark);
                    tvLogin.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(etPhone.getText().toString()) && !TextUtils.isEmpty(etPwd.getText().toString())) {
                    tvLogin.setBackgroundResource(R.drawable.shape_btn_login_normal);
                    tvLogin.setEnabled(true);
                } else {
                    tvLogin.setBackgroundResource(R.drawable.shape_btn_login_dark);
                    tvLogin.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        rlEye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mbDisplayFlg) {
                    // display password text, for example "123456"
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    ivEye.setImageResource(R.drawable.image_login_open);
                } else {
                    // hide password, display "."
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    ivEye.setImageResource(R.drawable.image_login_close);
                }
                etPwd.setSelection(etPwd.getText().toString().length());//将光标移至文字末尾
                mbDisplayFlg = !mbDisplayFlg;
                etPwd.postInvalidate();

            }
        });
        tvLoginForgetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,ResetPwdActivity.class));
            }
        });

    }
    /**
     * 登录
     */
    private void login() {
        if(!Utils.checkPhoneNo(etPhone.getText().toString())){
            ToastUitl.showImageToastTips(getResources().getString(R.string.error_phone));
            return;
        }
        tvLogin.setEnabled(false);

        Log.e(TAG, "----currentLat: "+ currentLat);
        Log.e(TAG, "----currentLon: "+ currentLon);
        Factoty.getViewModel(UserViewModel.class,LoginActivity.this).login(etPhone.getText().toString(),etPwd.getText().toString(),currentLat+","+currentLon);
        Factoty.getViewModel(UserViewModel.class,LoginActivity.this).getLoginliveData().observe(this, new Observer<BaseDto<LoginDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<LoginDto> dto) {
                tvLogin.setEnabled(true);
                hideLoadingDialog();
                if(dto.getCode()==Constant.Server.SUCCESS_CODE){
                    Set<String> set = new HashSet<>();
                    set.add("orgCode="+dto.getData().getOrgCode());
                    set.add("userId="+dto.getData().getUserId());
                    JPushInterface.setTags(LoginActivity.this,1001,set);

                    ToastUitl.showImageToastSuccess("登录成功");
                    SPUtil.putData(Constant.SP_VALUE.SP,Constant.SP_VALUE.LOGIN_DTO,dto.getData());
                    if(dto.getData()!=null){
                        //认证状态：1 跳到 开始考试 2 跳到 实名验证 3 跳到正在审核 4 跳到审核成功 5 跳到审核失败
                        if(dto.getData().getAuthStatus()==1){

                            startActivity(new Intent(LoginActivity.this, StartExamActivity.class));
                        }
                        else if(dto.getData().getAuthStatus()==2){
                            startActivity(new Intent(LoginActivity.this, RealNameAuthenticationActivity.class));
                        }
                        else if(dto.getData().getAuthStatus()==3){

                            Intent intent = new Intent(LoginActivity.this, IsReviewingActivity.class);
                            intent.putExtra("title", "实名认证");
                            startActivity(intent);


                        }
                       else  if(dto.getData().getAuthStatus()==4){

                            Intent intent = new Intent(LoginActivity.this, ReviewSuccessActivity.class);
                            intent.putExtra("title", "实名认证");
                            startActivity(intent);

                        }
                        else if(dto.getData().getAuthStatus()==5){

                            Intent intent = new Intent(LoginActivity.this, ReviewFailuerActivity.class);
                            intent.putExtra("title", "实名认证");
                            startActivity(intent);

                        }
                        else{
                            //
                            SPUtil.putData("login_sp","phone",etPhone.getText().toString());
                            startActivity(new Intent(LoginActivity.this,MainActivity.class));
                        }
                        finish();
                    }
                    else{
                        ToastUitl.showImageToastTips(dto.getMsg());
                    }


                }
                else{
                    ToastUitl.showImageToastTips(dto.getMsg());
                }
            }
        });
        showLoadingDialog();
    }
    private double currentLat;//当前位置的维度
    private double currentLon;//当前位置的经度
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation != null) {
            currentLat =bdLocation.getLatitude();
            currentLon = bdLocation.getLongitude();
            Log.e(TAG, "----currentLat: "+ currentLat);
            Log.e(TAG, "----currentLon: "+ currentLon);
            MyApplication.getInstance().mLocationClient.stop();

        }
    }

}
